<?php 

/**
 * sfWidgetFormPropelChoice represents a choice widget for a model.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormPropelChoice.class.php 12803 2008-11-09 07:26:18Z fabien $
 */
class sfWidgetPropelAjaxBindCheckBoxPopup  extends sfWidgetFormPropelChoice
{
    /**
   * Configures the current widget.
   *
   * Available options:
   *
   *  * url:            The URL to call to get the choices to use (required)
   *  * config:         A JavaScript array that configures the JQuery autocompleter widget
   *  * value_callback: A callback that converts the value before it is displayed
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetForm
   */
    protected function configure($options = array(), $attributes = array())
    {
        sfContext::getInstance()->getConfiguration()->loadHelpers('I18N');
        sfContext::getInstance()->getResponse()->addStylesheet('/sfCustomWidgetsPlugin/css/sfWidgetPropelAjaxBindCheckBoxPopup.css');
        $this->addOption('change_widget');
        $this->addOption('url' , sfContext::getInstance()->getController()->genUrl('@custom_widgets_bind_ajax'));
        $this->addOption('pk' ,'id');
        $this->addOption('fk' , null);
        $this->addOption('culture' , sfContext::getInstance()->getUser()->getCulture());
        
        parent::configure($options, $attributes);
    }

    /**
   * @param  string $name        The element name
   * @param  string $value       The date displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        //echo $value;
        //$this->setOption( 'expanded' , true );

        $fk = $this->getOption('fk');
        $fk = !empty($fk) ? $fk : $this->getOption('change_widget');


        if( $this->getOption('multiple') ){
            $name = "{$name}[]";
        }
        $this_id = $this->generateId($name);

        $value = is_array($value) ? $value : array($value);
        $value_complex = !empty($value[0]) ? '[ "'.trim(implode('","',$value),',') .'" ]' : '';

        //die($this_id);



        $culture = $this->getOption('culture');

        //echo $value_complex;

        $pop_up_data_lbl = __('View');
        $script = "
<script type='text/javascript'>
  var call_back_method_{$this_id} = null;
  jQuery(function($) {";

        $html = "<div class='{$this_id} {$culture} parent_con'>";

        $html .= "<div class='button'><a class='popup-link' href='javascript:;' tmp_data='{$value_complex}' >{$pop_up_data_lbl}</a></div>";
        $html .= "<ul class='popup-cont-ul'></ul>";
        if($this->getOption('change_widget',null)){


            $add_empty = $this->getOption('add_empty');
            $content = !empty($add_empty) ? '<option value="" class="empty">'.(is_string($add_empty) ? $add_empty : '').'</option>' : null;

            $select_attrs = array('id' => $this_id, 'name' => $name);
            if( $this->getOption('multiple') ){
                $select_attrs['multiple'] = 'multiple';
            }


            $main_widget = $this->renderContentTag('select' , $content , $select_attrs );


            $change_widget = preg_replace('/([a-zA-Z0-9_]*)\[.*/','\1['.$this->getOption('change_widget').']' ,$name);

            $change_w_id = $this->generateId($change_widget);


            $script .= "
			function popup_link_click_{$this_id}(){
				ja = $('div.{$this_id} a.popup-link');
			    if(!ja.attr('tmp_data') || ja.attr('tmp_data')=='null'){
				alert('There is no data choosen from parent');
				return ;
				}
				dialog_{$this_id}();			
			}

				$('div.{$this_id} a.popup-link').click(function(){
					
				$('#{$change_w_id}').change();
					call_back_method_{$this_id} = 'popup_link_click_{$this_id}';
					

					return false;
					});//click
			
		      $('#{$change_w_id}').change(function(){
			    	data = $('#{$change_w_id}').val();
		      		$('div.{$this_id} a.popup-link').attr('tmp_data', data );
					$('#{$this_id}').load('".sprintf($this->getOption('url')."?_='+Math.random()+'&model=%s&peer_method=%s&fk=%s&add_empty=%s&fk_value='+data
						,function(){
							list_checks_{$this_id}(); 
							if(call_back_method_{$this_id}!=null){eval(call_back_method_{$this_id}+'()');}
						});"
            ,$this->getOption('model'),$this->getOption('peer_method'),$fk,urlencode($add_empty))."
		      });
		      call_back_method_{$this_id} = null;
		      
		      if($('#{$change_w_id}').val()){
		        $('#{$change_w_id}').change();
		      }
		      
		      
		      $('#{$this_id}').attr('tmp_data','{$value_complex}');
		      ";
        } else {

            $main_widget = parent::render( $name , $value );

            // this for checkboxes in the dialog
            $this->setOption('expanded',true);



            $check_boxes = str_replace("'","\\'",preg_replace('/\s/',' ',parent::render( $name , $value )));
            $script .= "
				$('div.{$this_id} a.popup-link').click(function(){
						dialog_{$this_id}();
					return false;
				});//click
			";

        }

        $html.="</div>";

$title = __('Choose '.$this->getOption('label'));
$msg1 = __("Choose & close");
$msg2 = __("Check all");
        $script .=<<<EOF
			
function dialog_{$this_id}(){



	content = "<ul>";
    //content += "<li><a href='#' onclick='elems = $(\".{$this_id}.pop-con input[type=checkbox]\"); if(this.checked)elems.attr(\"checked\",\"checked\");else elems.removeAttr(\"checked\");return false'>$msg2</a></li>";
    content += '<li><a href="#" onclick="jthis = $(this);elems = $(\'.{$this_id}.pop-con input[type=checkbox]\'); if(jthis.attr(\'checked\')){jthis.removeAttr(\'checked\');elems.removeAttr(\'checked\');}else {elems.attr(\'checked\',\'checked\');jthis.attr(\'checked\',\'checked\')};return false">Check all</a></li>';
	$('#{$this_id} option').each(function(){
		if(this.value){
			content += "<li><input type='checkbox' name='dummy[]' id='{$this_id}_num_"+this.value+"' value='"+this.value+"'><label for='{$this_id}_num_"+this.value+"'>"+$(this).html()+"</label></li>";
		}
	});

	
	content +="</ul>";
	\$pop_cont =  $('<div class=\"{$this_id} pop-con {$culture}\" title=\"{$title}\"></div>').html(content);

	\$pop_cont.dialog({
	     open:function(){
	     	list_checks_{$this_id}();
	     }
		,buttons:{
		"$msg1": function(){
			//onchange ,, any attached elment will have trigger change
			arr = new Array();
			$('.{$this_id}.pop-con input:checked')
			   .each(
					function(i){
						arr[i] = this.value;
					});//each
			  $('#{$this_id}').val(  arr );
			  $('#{$this_id}').change();
			  list_checks_{$this_id}();
				$(this).dialog('close');
			  } //choose
		}//buttons
	})//dialog
}
var {$this_id}_tmp_data_loaded_first_time = false;
function list_checks_{$this_id}(use_tmp_data){

    arr2 = null;
        if(!{$this_id}_tmp_data_loaded_first_time && $('#{$this_id} option').length > 1){
            old_data = $('#{$this_id}').attr('tmp_data') ? $('#{$this_id}').attr('tmp_data') : "[]";
        	eval("arr2=" + old_data + ";");
        	{$this_id}_tmp_data_loaded_first_time = true;
            //$('#{$this_id}').attr('tmp_data','');
        }
	arr = $('#{$this_id}').val();
	if($.isArray(arr2) ){
		
		if(!arr) {
			arr = [];
		}
		merged_arr = $.merge( arr , arr2);
		
		$('#{$this_id}').val( merged_arr );
		
	}
	else if( $.isArray(arr) ){
	   	$('#{$this_id}').val( arr );
	}
	
	//console.log('$this_id');
	//console.log(arr);
	

	

	
	
	$('div.{$this_id} ul.popup-cont-ul').empty();
	$('.{$this_id}.pop-con input:checked').removeAttr('checked');
	$('#{$this_id} option:selected').each(function(){
	$('div.{$this_id}').addClass('parent_con_filled');
		val = $(this).val();
		content = $(this).html();
		$('.{$this_id}.pop-con input:[value='+val+']').attr('checked','checked');
		if(val){
			$('div.{$this_id} ul.popup-cont-ul').append(
				"<li value="+val+" class='sf_admin_action_delete' > <a href=\"javascript:;\" onclick=\"$('#{$this_id} option:[value="+val+"]').attr('selected',false);$('#{$this_id}').change();$(this).parent().remove();\">remove</a> "+content+"</li>"
			);//apend
		}//if val
	});

}
list_checks_{$this_id}();

$('#{$this_id}').hide();

EOF;

        $script.="  });\n</script>";


        return $html.$main_widget.$script;

    }

    /**
   * Gets the stylesheet paths associated with the widget.
   *
   * @return array An array of stylesheet paths
   */
    public function getStylesheets()
    {
        //return array('/sfCustomWidgetsPlugin/css/jquery.autocompleter.css' => 'all');
        return array();
    }

    /**
   * Gets the JavaScript paths associated with the widget.
   *
   * @return array An array of JavaScript paths
   */
    public function getJavascripts()
    {
        //return array('/sfCustomWidgetsPlugin/js/jquery.autocompleter.js');
        return array();
    }
}